//
//  ImageGridView.swift
//  CooImage
//
//  Created by jerry on 2025/8/16.
//

import SwiftUI

struct ImageGridView: View {
    var imageURLs: [URL]
    var onSelectImage: (URL) -> Void
    
    @State private var gridLayout = [GridItem(.adaptive(minimum: 150))]
    @State private var isListView = false
    @State private var thumbnailCache: [URL: NSImage] = [:]
    @State private var loadingThumbnails = false
    
    var body: some View {
        VStack {
            HStack {
                Text("图片浏览器")
                    .font(.headline)
                
                Spacer()
                
                if loadingThumbnails {
                    ProgressView()
                        .scaleEffect(0.7)
                        .padding(.trailing, 8)
                }
                
                Button(action: {
                    isListView.toggle()
                }) {
                    Image(systemName: isListView ? "square.grid.2x2" : "list.bullet")
                        .frame(width: 20, height: 20)
                }
                .buttonStyle(.borderless)
                .help(isListView ? "切换到网格视图" : "切换到列表视图")
            }
            .padding(.horizontal)
            .padding(.top, 8)
            
            if isListView {
                // 列表视图
                List {
                    ForEach(imageURLs, id: \.self) { url in
                        HStack {
                            ThumbnailView(url: url, thumbnailCache: $thumbnailCache, size: CGSize(width: 60, height: 60))
                            
                            Text(url.lastPathComponent)
                                .lineLimit(1)
                                .truncationMode(.middle)
                            
                            Spacer()
                        }
                        .padding(.vertical, 4)
                        .contentShape(Rectangle())
                        .onTapGesture {
                            onSelectImage(url)
                        }
                    }
                }
            } else {
                // 网格视图
                ScrollView {
                    LazyVGrid(columns: gridLayout, spacing: 20) {
                        ForEach(imageURLs, id: \.self) { url in
                            VStack {
                                ThumbnailView(url: url, thumbnailCache: $thumbnailCache, size: CGSize(width: 150, height: 120))
                                
                                Text(url.lastPathComponent)
                                    .font(.caption)
                                    .lineLimit(1)
                                    .truncationMode(.middle)
                            }
                            .padding(.bottom, 5)
                            .contentShape(Rectangle())
                            .onTapGesture {
                                onSelectImage(url)
                            }
                        }
                    }
                    .padding()
                }
            }
        }
        .frame(minWidth: 600, minHeight: 400)
        .onAppear {
            loadThumbnails()
        }
    }
    
    private func loadThumbnails() {
        guard !imageURLs.isEmpty else { return }
        
        loadingThumbnails = true
        
        // 在后台线程加载缩略图
        DispatchQueue.global(qos: .userInitiated).async {
            // 创建一个临时缓存
            var tempCache: [URL: NSImage] = [:]
            
            // 批量加载前20张图片的缩略图
            let initialBatch = min(20, imageURLs.count)
            for i in 0..<initialBatch {
                let url = imageURLs[i]
                if let thumbnail = NSImage(contentsOf: url) {
                    // 创建缩略图
                    let thumbnailSize = NSSize(width: 150, height: 150)
                    let resizedThumbnail = NSImage(size: thumbnailSize)
                    
                    resizedThumbnail.lockFocus()
                    thumbnail.draw(in: NSRect(x: 0, y: 0, width: thumbnailSize.width, height: thumbnailSize.height),
                                  from: NSRect(x: 0, y: 0, width: thumbnail.size.width, height: thumbnail.size.height),
                                  operation: .copy,
                                  fraction: 1.0)
                    resizedThumbnail.unlockFocus()
                    
                    tempCache[url] = resizedThumbnail
                }
            }
            
            // 在主线程更新UI
            DispatchQueue.main.async {
                self.thumbnailCache = tempCache
                self.loadingThumbnails = false
                
                // 继续加载剩余的图片
                if imageURLs.count > initialBatch {
                    loadRemainingThumbnails(startIndex: initialBatch)
                }
            }
        }
    }
    
    private func loadRemainingThumbnails(startIndex: Int) {
        DispatchQueue.global(qos: .utility).async {
            var tempCache = self.thumbnailCache
            
            // 每批加载10张图片
            let batchSize = 10
            let endIndex = min(startIndex + batchSize, imageURLs.count)
            
            for i in startIndex..<endIndex {
                let url = imageURLs[i]
                if let thumbnail = NSImage(contentsOf: url) {
                    // 创建缩略图
                    let thumbnailSize = NSSize(width: 150, height: 150)
                    let resizedThumbnail = NSImage(size: thumbnailSize)
                    
                    resizedThumbnail.lockFocus()
                    thumbnail.draw(in: NSRect(x: 0, y: 0, width: thumbnailSize.width, height: thumbnailSize.height),
                                  from: NSRect(x: 0, y: 0, width: thumbnail.size.width, height: thumbnail.size.height),
                                  operation: .copy,
                                  fraction: 1.0)
                    resizedThumbnail.unlockFocus()
                    
                    tempCache[url] = resizedThumbnail
                }
            }
            
            // 在主线程更新UI
            DispatchQueue.main.async {
                self.thumbnailCache = tempCache
                
                // 继续加载剩余的图片
                if endIndex < imageURLs.count {
                    loadRemainingThumbnails(startIndex: endIndex)
                }
            }
        }
    }
}

// 缩略图视图组件
struct ThumbnailView: View {
    let url: URL
    @Binding var thumbnailCache: [URL: NSImage]
    let size: CGSize
    
    var body: some View {
        Group {
            if let cachedImage = thumbnailCache[url] {
                Image(nsImage: cachedImage)
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(width: size.width, height: size.height)
            } else {
                // 显示占位符
                Image(systemName: "photo")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(width: size.width, height: size.height)
                    .foregroundColor(.gray)
            }
        }
    }
}

struct ImageGridView_Previews: PreviewProvider {
    static var previews: some View {
        ImageGridView(
            imageURLs: [],
            onSelectImage: { _ in }
        )
    }
}